<?php

namespace App\Services;

use App\Models\User;
use App\Repositories\UserRepository;
use App\Exceptions\BusinessException;
use App\Services\CacheService;
use App\Services\LogService;
use Illuminate\Support\Facades\Log;

/**
 * 微信认证服务模拟实现
 * 用于开发和测试环境，不调用真实微信API
 */
class WechatAuthServiceMock
{
    protected $userRepository;
    protected $cacheService;
    protected $logService;

    public function __construct(UserRepository $userRepository, CacheService $cacheService, LogService $logService)
    {
        $this->userRepository = $userRepository;
        $this->cacheService = $cacheService;
        $this->logService = $logService;
    }

    /**
     * 微信小程序登录（模拟实现）
     */
    public function login(string $code, array $userInfo = []): User
    {
        try {
            // 获取模拟的微信openid
            $openid = $this->getMockOpenid($code);
            
            if (!$openid) {
                throw new BusinessException('微信授权失败', 40001);
            }

            // 创建或更新用户
            $userData = [
                'openid' => $openid,
                'nickname' => $userInfo['nickName'] ?? '测试用户',
                'avatar' => $userInfo['avatarUrl'] ?? 'https://via.placeholder.com/100x100?text=User',
                'phone' => $userInfo['phoneNumber'] ?? null,
                'gender' => $userInfo['gender'] ?? 0,
                'city' => $userInfo['city'] ?? '北京',
                'province' => $userInfo['province'] ?? '北京',
                'country' => $userInfo['country'] ?? '中国',
                'language' => $userInfo['language'] ?? 'zh_CN',
            ];

            $user = $this->userRepository->createOrUpdateByOpenid($openid, $userData);

            // 缓存用户信息
            $this->cacheService->putUser($user->id, $user, CacheService::TTL_MEDIUM);

            // 记录登录活动
            $this->logService->logUserActivity('用户登录（模拟）', $user, [
                'login_method' => 'wechat_mock',
                'ip' => request()->ip(),
                'user_agent' => request()->userAgent(),
            ]);

            return $user;

        } catch (BusinessException $e) {
            throw $e;
        } catch (\Exception $e) {
            Log::error('微信登录失败（模拟）', [
                'code' => $code,
                'error' => $e->getMessage(),
                'trace' => $e->getTraceAsString()
            ]);
            
            throw new BusinessException('登录失败，请重试', 50003);
        }
    }

    /**
     * 获取模拟的微信openid
     */
    private function getMockOpenid(string $code): ?string
    {
        // 模拟微信API返回
        if (empty($code)) {
            return null;
        }
        
        // 生成固定的openid用于测试
        return 'mock_openid_' . md5($code);
    }

    /**
     * 刷新用户信息
     */
    public function refreshUserInfo(User $user, array $userInfo): User
    {
        $updateData = [];
        
        if (isset($userInfo['nickName'])) {
            $updateData['nickname'] = $userInfo['nickName'];
        }
        
        if (isset($userInfo['avatarUrl'])) {
            $updateData['avatar'] = $userInfo['avatarUrl'];
        }
        
        if (isset($userInfo['phoneNumber'])) {
            $updateData['phone'] = $userInfo['phoneNumber'];
        }

        if (!empty($updateData)) {
            $this->userRepository->update($user->id, $updateData);
            $user->refresh();
        }

        return $user;
    }

    /**
     * 验证用户状态
     */
    public function validateUser(User $user): void
    {
        if (!$user->is_active) {
            throw new BusinessException('用户已被禁用', 40002);
        }
    }
}
